package com.itcast.n1_内存调优;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: jvm
 * @description:
 * @author: flyduck
 * @create: 2024-10-16 14:50
 **/
public class Test05_内存泄漏问题1_hashMap的key对象没有重写equals和hashcode方法 {
    public static long count = 0;
    public static Map<Student2,Long> map = new HashMap<>();
    public static void main(String[] args) throws InterruptedException {
        while (true){
            if(count++ % 100 == 0){
                Thread.sleep(10);
            }
            Student2 student2 = new Student2();
            student2.setId(1);
            student2.setName("张三");
            map.put(student2,1L);//按理来说，我放入student是一个人，应该只会存在一份，但因为没有重写hashcode方法和equals方法
        }
    }
}

@Getter
@Setter
class Student2 {
    private int id;
    private String name;
    private byte[] bytes = new byte[1024 * 1024];

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Student2 student2 = (Student2) o;

        return new EqualsBuilder()
                .append(id, student2.id)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(id)
                .toHashCode();
    }
}
